package com.hejia.alauda.service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.stereotype.Service;
import com.hejia.alauda.entity.BankCard;
import com.hejia.alauda.entity.BankCard.Status;
import com.hejia.alauda.entity.Message;
import com.hejia.alauda.entity.PayOrder;
import com.hejia.alauda.entity.Product;
import com.hejia.alauda.entity.User;
import com.hejia.alauda.entity.example.PayOrderExample;
import com.hejia.alauda.persistence.mybatis.PayOrderMapper;
import com.hejia.alauda.persistence.mybatis.UserMapper;
import com.hejia.alauda.utils.Pager;
import com.hejia.hermes.entity.SMS;
import com.hejia.hermes.service.SMSService;

@Service
public class PayOrderServiceImpl implements PayOrderService {

	private static final Log logger = LogFactory
			.getLog(PayOrderServiceImpl.class);

	@Resource
	private PayOrderMapper payOrderMapper;

	@Resource(name = "sendSMS")
	private SMSService smsService;

	@Resource
	private PaymentService paymentService;

	@Resource
	private RookieService rookieService;

	@Resource
	private UserMapper userMapper;

	@Resource
	private MessageService messageService;

	@Override
	public PayOrder findPayOrderByPayNumber(String payNumber) {
		PayOrderExample example = new PayOrderExample();
		example.appendCriterion("payNumber =", payNumber);
		return this.payOrderMapper.selectOneByExample(example);
	}

	@Override
	public void handlePayOrderSuccessNotify(Executor executor, String payNumber) {

		final PayOrder payOrder = this.findPayOrderByPayNumber(payNumber);

		// 订单终态不再处理
		if (payOrder.getStatus().equals(PayOrder.Status.STATUS_PAID)
				|| payOrder.getStatus().equals(PayOrder.Status.STATUS_FAILED)) {
			return;
		}

		// 绑卡
		BankCard bankCard = payOrder.getBankCard();
		final User user = bankCard.getUser();
		if (bankCard.getStatus().equals(Status.UNBIND)) {
			bankCard.setStatus(Status.BINDED);
			paymentService.saveBankCard(bankCard);

			// 更新身份认证信息
			user.setIdCard(bankCard.getCertId());
			user.setRealName(bankCard.getUserName());
			user.setModifyDate(new Date());
			userMapper.updateByPrimaryKey(user);
		}

		payOrder.setModifyDate(new Date());
		payOrder.setNotifyTime(new Date());
		payOrder.setStatus(PayOrder.Status.STATUS_PAID.toString());

		if (this.payOrderMapper.updateByPrimaryKey(payOrder) < 1) {
			throw new RuntimeException("更新支付订单失败");
		}

		try {
			if (payOrder.getType().equals(
					PayOrder.Type.ROOKIE_EXPERIENCE.toString())) {
				rookieService.addRookieExperienceBonus(payOrder);

				// 红包金额=收益+1分支付
				Product product = this.rookieService.createRookieProduct();
				BigDecimal bonus = product.getInvestmentIncome(
						product.getMaxAmount()).add(BigDecimal.valueOf(0.01));
				DecimalFormat decimalFormat = new DecimalFormat(",##0.00");

				// 发送通知短信
				final String message = String.format(
						"尊敬的%s，您已成功购买%s。红包%s元，可到[我的红包]提现。客服热线:400-871-8080",
						user.getRealName(), payOrder.getDescription(),
						decimalFormat.format(bonus));

				// 执行打款
				executor.execute(new Runnable() {

					@Override
					public void run() {

						// 发送App消息
						messageService.sendAppMessage(user,
								Message.CATEGORY_BONUS, message, null);

						// 发送短信
						SMS sms = new SMS();
						sms.setMobile(user.getMobile());
						sms.setMessage(message);
						sms.setChannel("alauda_order");
						smsService.sendSMS(sms);
					}
				});
			}
		} catch (Exception e) {
			logger.error("添加新手体验红包失败", e);
		}
	}

	@Override
	public void handlePayOrderFailureNotify(String payNumber) {

		PayOrder payOrder = this.findPayOrderByPayNumber(payNumber);

		// 订单终态不再处理
		if (payOrder.getStatus().equals(PayOrder.Status.STATUS_PAID)
				|| payOrder.getStatus().equals(PayOrder.Status.STATUS_FAILED)) {
			return;
		}

		payOrder.setModifyDate(new Date());
		payOrder.setNotifyTime(new Date());
		payOrder.setStatus(PayOrder.Status.STATUS_FAILED.toString());

		if (this.payOrderMapper.updateByPrimaryKey(payOrder) < 1) {
			throw new RuntimeException("更新支付订单失败");
		}
	}

	@Override
	public Pager<PayOrder> findPayOrders(String keyword,
			PayOrder.Status status, Pager<PayOrder> pager) {

		Map<String, Object> map = new HashMap<String, Object>();

		if (StringUtil.isNotBlank(keyword)) {
			map.put("keyword", keyword);
		}
		if (status != null) {
			map.put("status", status);
		}

		map.put("startNumber", pager.getStartNumber());
		map.put("pageSize", pager.getPageSize());

		pager.setList(this.payOrderMapper.selectPayOrders(map));
		pager.setTotalCount(this.payOrderMapper.selectPayOrdersCount(map));

		return pager;

	}

	@Override
	public PayOrder findPayOrderById(long id) {
		return payOrderMapper.selectByPrimaryKey(id);
	}

}
